<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

/**
 * @property mixed group_id
 */
class XXlBaseForm extends Model
{
    use HasDateTimeFormatter;

    protected $table = 't_t__test_forms';

    protected $fillable = [
        "name",
        "phone",
        "channel",
        "question_data",
        'url',
        'group_id',
        'remark',
        'leads_id',
        'created_at',
        'dispatch_date',
        'ip',
        'city',
        'state_name',
    ];

    protected $casts = [
        "question_data" => "json"
    ];


    static public $channelList = [
        'toutiao' => '头条',
        'oppo' => 'OPPO',
    ];

    public function user()
    {
        return $this->belongsToMany(Administrator::class, 'admin_user_has_test_form', 'form_id', 'user_id');
    }

    public function group()
    {
        return $this->belongsTo(UserGroup::class, 'group_id');
    }

    /**
     * 为传入的 表单 ID 修改  分配时间
     *
     * @param $id   array|string|number
     * @param $date string|Carbon
     */
    public static function setDispatchDate($id, $date)
    {
        static::query()
            ->whereIn('id', (array)$id)
            ->update([
                'dispatch_date' => $date
            ]);
    }

    public function toArray()
    {
        $row = parent::toArray(); // TODO: Change the autogenerated stub
        $row['question_data'] = json_encode($row['question_data'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: " ";
        $row['_user'] = data_get($row, 'user.0.name');

        return $row;
    }

}
